import BaseDialog from "components/BaseDialog";
import dayjs from "dayjs";
import { useEffect, useState } from "react";
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  ScrollView,
} from "react-native";
import BouncyCheckboxGroup, {
  type ICheckboxButton,
} from "react-native-bouncy-checkbox-group";
import { getStorageData, setStorageData } from "utils";
import toast from "utils/toast";
import translate from "utils/translate";
type FormData = {
  modelName: string;
  className: string;
  point: string;
};
type FormKeys = keyof FormData;
export default ({
  navigation,
  route: { params },
}: RootStackScreenProps<"addModel">) => {
  const [form, setForm] = useState<Omit<typeof params, "index">>({
    modelName: "",
    className: "",
    point: "",
  });
  const [defaultId, setDefaultId] = useState("");
  useEffect(() => {
    const { index, ...rest } = params;
    getStorageData("defaultGoods").then((value) => {
      // const defaultId = value;
      setDefaultId(value ?? "");
    });
    setForm(() => {
      staticData.find;
      return {
        ...rest,
      };
    });
    setCheck(
      (staticData.find((item) => item.text === params.point)?.id as string) ??
        ""
    );
  }, []);
  const onDel = async () => {
    const StorageData = await getStorageData("classList");
    const classList = StorageData ? JSON.parse(StorageData) : [];
    classList.splice(params.index, 1);
    setStorageData("classList", JSON.stringify(classList)).then(() => {
      setModalVisible(false);
      navigation.goBack();
    });
  };
  const [modalVisible, setModalVisible] = useState(false);
  const handleSave = async () => {
    if (
      (form.className?.replaceAll(/[\u4e00-\u9fa5]/g, "aa")?.length ?? 0) >
      (List[1].maxLength ?? 0)
    ) {
      return translate("main.tooLong");
    }
    if (form.className && form.point) {
      const StorageData = await getStorageData("classList");
      const classList = StorageData ? JSON.parse(StorageData) : [];
      if (params.index === 0 || params.index) {
        classList.splice(params.index, 1, {
          ...classList[params.index],
          ...form,
        });
      } else {
        classList.unshift({
          ...form,
          createTime: dayjs().format("YYYY-MM-DD HH:mm"),
          id: new Date().valueOf(),
        });
      }
      setStorageData("classList", JSON.stringify(classList)).then(() => {
        if (params.index || params.index === 0) {
          navigation.goBack();
        } else {
          navigation.navigate("classification", {});
        }
      });
    } else {
      translate("main.toCmplete");
    }
  };
  const [isCheck, setCheck] = useState("");
  const handleChange = (value: string, key: FormKeys) => {
    setForm((prevForm) => ({
      ...prevForm,
      [key]: value,
    }));
  };
  const addDefault = () => {
    if (defaultId) {
      if (defaultId == params.id) {
        setStorageData("defaultGoods", "").then(() => {
          setDefaultId("");
        });
      } else {
        setStorageData("defaultGoods", params.id + "").then(() => {
          setDefaultId(params.id + "");
        });
      }
    } else {
      setStorageData("defaultGoods", params.id + "").then(() => {
        setDefaultId(params.id + "");
      });
    }
  };
  const staticData: ICheckboxButton[] = [
    {
      id: "0",
      text: "0.00",
      fillColor: "#0081ff",
      textStyle: {
        textDecorationLine: "none",
      },
    },
    {
      id: "1",
      text: "0.0",
      fillColor: "#0081ff",
      style: {
        marginLeft: 30,
        marginRight: 30,
      },
      textStyle: {
        textDecorationLine: "none",
      },
    },
    {
      id: "2",
      text: "0",
      fillColor: "#0081ff",
      textStyle: {
        textDecorationLine: "none",
      },
    },
  ];
  const List = [
    {
      label: translate("main.model"),
      prop: "modelName",
    },
    {
      label: translate("main.name"),
      prop: "className",
      placeholder: translate("main.toCmplete"),
      maxLength: 20,
      multiline: true,
      numberOfLines: 2,
    },
    {
      label: translate("main.point"),
      prop: "point",
    },
  ];
  return (
    <View
      style={{
        flex: 1,
      }}
    >
      <ScrollView
        style={{
          flex: 1,
          paddingTop: 20,
          paddingBottom: 20,
        }}
        contentContainerStyle={{
          alignItems: "center",
        }}
      >
        {List.map((item) => {
          return (
            <View
              key={item.label}
              style={{
                flexDirection: "row",
                alignItems: "center",
                marginBottom: 20,
                width: "90%",
              }}
            >
              <Text
                style={{
                  width: 80,
                }}
              >
                {item.label}
              </Text>
              {item.prop !== "point" && (
                <View
                  style={{
                    flexDirection: "row",
                    alignItems: "center",
                    borderWidth: 1,
                    borderRadius: 8,
                    marginLeft: 10,
                    marginRight: 10,
                    borderColor: "#ccc",
                    padding: 8,
                    width: 200,
                    flex: 1,
                    justifyContent: "space-between",
                  }}
                >
                  <TextInput
                    onChangeText={(value) => {
                      handleChange(value, item.prop as FormKeys);
                    }}
                    defaultValue={form[item.prop as FormKeys]}
                    style={{
                      flex: 5,
                    }}
                    multiline={item.multiline}
                    numberOfLines={item.numberOfLines}
                    placeholder={item.placeholder}
                  ></TextInput>
                  {item.prop !== "modelName" && (
                    <Text style={{ flex: 1, minWidth: 10, marginLeft: 5 }}>
                      {form[item.prop as FormKeys]?.replaceAll(
                        /[\u4e00-\u9fa5]/g,
                        "aa"
                      )?.length ?? 0}
                      /{item.maxLength}
                    </Text>
                  )}
                </View>
              )}
              {item.prop == "point" && (
                <BouncyCheckboxGroup
                  data={staticData}
                  style={{
                    marginLeft: 10,
                  }}
                  // @ts-ignore
                  initial={isCheck}
                  onChange={(selectedItem: ICheckboxButton) => {
                    setForm((prevForm) => {
                      return {
                        ...prevForm,
                        point: selectedItem.text as string,
                      };
                    });
                  }}
                />
              )}
            </View>
          );
        })}
        <TouchableOpacity style={styles.button} onPress={handleSave}>
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("main.save")}
          </Text>
        </TouchableOpacity>
        {params.modelName === "P4" && (params.index === 0 || params.index) && (
          <TouchableOpacity
            style={{ ...styles.button, backgroundColor: "#4768f3" }}
            onPress={() => {
              addDefault();
            }}
          >
            <Text
              style={{
                textAlign: "center",
                color: "#fff",
              }}
            >
              {
                // defaultId==params.id?'取消默认':
                defaultId
                  ? defaultId == params.id
                    ? translate("main.undefault")
                    : translate("main.ModifyDefault")
                  : translate("main.AddDefault")
              }
            </Text>
          </TouchableOpacity>
        )}
        {(params.index === 0 || params.index) && (
          <TouchableOpacity
            style={{
              ...styles.button,
              backgroundColor: "#e54d42",
            }}
            onPress={() => {
              setModalVisible(true);
            }}
          >
            <Text
              style={{
                textAlign: "center",
                color: "#fff",
              }}
            >
              {translate("main.delete")}
            </Text>
          </TouchableOpacity>
        )}
        <BaseDialog
          visible={modalVisible}
          content={translate("main.sure")}
          title={translate("main.tip") + "!"}
          handleCancel={() => {
            setModalVisible(false);
          }}
          handleSubmit={() => {
            onDel();
          }}
        ></BaseDialog>
      </ScrollView>
    </View>
  );
};
const styles = StyleSheet.create({
  button: {
    backgroundColor: "#0A59F7",
    width: "60%",
    height: 50,
    marginBottom: 30,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    alignSelf: "center",
  },
});
